package no.runeway.logentry;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LogEntryParserImpl implements LogEntryParser {

	@Override
	public List<LogEntry> getLogEntriesFromBufferedReader(BufferedReader reader) throws IOException {

		List<LogEntry> logEntries = new ArrayList<LogEntry>();

		for (String line = reader.readLine(); line != null; line = reader.readLine()) {
			logEntries.add(getLogEntryFromLogline(line));
		}
		
		return logEntries;
	}

	@Override
	public LogEntry getLogEntryFromLogline(String logline) {

		LogEntry logEntry = new LogEntry();

		List<String> separatedBySpace = Arrays.asList(logline.split(" "));
		List<String> separatedByQuote = Arrays.asList(logline.split("\""));

		logEntry.setRemoteHost(separatedBySpace.get(0));
		logEntry.setServer(separatedBySpace.get(1));
		logEntry.setRemoteUser(separatedBySpace.get(2));
		logEntry.setTimeOfRequest(logline.substring(
				logline.indexOf("[", 0) + 1, logline.indexOf("]", 0)));
		logEntry.setFirstLineOfRequest(separatedByQuote.get(1));
		logEntry.setStatusCode(separatedBySpace.get(8));
		logEntry.setBytes(separatedBySpace.get(9));
		logEntry.setReferrer(separatedByQuote.get(3));
		logEntry.setUserAgent(separatedByQuote.get(5));

		return logEntry;
	}

}
